import { API_BASE_URL } from '@/config/env';

export interface Target {
  to_type: 'User' | 'Group';
  to_id: string;
}

export interface User {
  id: string;
  name: string;
  email: string;
  snowflake_id?: string;
  open_id?: string;
  file_name?: string; // 头像文件名
}

export const sendMessage = async (
  userId: string,
  target: Target,
  content: string,
  fileUrl?: string,
  fileName?: string,
  fileType?: string
): Promise<void> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${API_BASE_URL}/api/messages`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify({
      from_user_id: userId,
      target,
      message: content,
      file_url: fileUrl,
      file_name: fileName,
      file_type: fileType,
    }),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '发送消息失败' }));
    throw new Error(error.message || '发送消息失败');
  }
};

export const createUser = async (name: string, email: string, password: string): Promise<User> => {
  const response = await fetch(`${API_BASE_URL}/api/users`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name, email, password }),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '创建用户失败' }));
    throw new Error(error.message || '创建用户失败');
  }

  return response.json();
};

export const getUser = async (userIdOrSnowflakeIdOrUsername: string): Promise<User> => {
  const token = localStorage.getItem('token');
  
  if (!token) {
    throw new Error('请先登录');
  }
  
  // 支持用户ID、雪花ID或用户名
  const id = userIdOrSnowflakeIdOrUsername.trim();
  if (!id) {
    throw new Error('请输入用户ID或用户名');
  }
  
  // 对用户名进行URL编码
  const encodedId = encodeURIComponent(id);
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/users/${encodedId}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      let errorMessage = '获取用户信息失败';
      
      // 尝试解析错误信息
      try {
        const error = await response.json();
        errorMessage = error.message || error.msg || errorMessage;
      } catch (e) {
        // 如果解析失败，使用状态码判断
        if (response.status === 401) {
          errorMessage = '认证失败，请重新登录';
        } else if (response.status === 404) {
          errorMessage = `用户不存在（用户名或ID: ${id}）`;
        } else if (response.status === 500) {
          errorMessage = '服务器内部错误';
        }
      }
      
      // 对于 404 错误（用户不存在），只记录 debug 信息，不打印错误日志
      // 因为这在群聊中很常见（用户可能已被删除或数据不一致）
      if (response.status === 404) {
        // 只在开发模式下记录详细信息
        if (import.meta.env.DEV) {
          console.debug('用户不存在（静默处理）:', {
            status: response.status,
            url: `${API_BASE_URL}/api/users/${encodedId}`,
            message: errorMessage,
          });
        }
      } else {
        // 对于其他错误，正常打印错误日志
        console.error('获取用户信息失败:', {
          status: response.status,
          statusText: response.statusText,
          url: `${API_BASE_URL}/api/users/${encodedId}`,
          message: errorMessage,
        });
      }
      
      throw new Error(errorMessage);
    }

    const user = await response.json();
    
    // 确保返回的用户ID是雪花ID（如果存在），否则使用数据库ID
    // 注意：后端现在将 snowflake_id 序列化为字符串，避免 JavaScript 精度丢失
    let userId: string;
    if (user.snowflake_id !== null && user.snowflake_id !== undefined) {
      // snowflake_id 现在应该是字符串类型（后端序列化为字符串）
      userId = String(user.snowflake_id);
    } else {
      userId = String(user.id);
    }
    
    return {
      id: userId,
      name: user.name,
      email: user.email,
      snowflake_id: user.snowflake_id ? String(user.snowflake_id) : undefined,
      open_id: user.open_id,
    };
  } catch (error: any) {
    // 网络错误或其他错误
    if (error.message) {
      throw error;
    }
    console.error('获取用户信息网络错误:', error);
    throw new Error('网络错误，请检查后端服务是否运行');
  }
};

export interface Message {
  message_id: string;
  from_user_id: string;
  to_user_id: string;
  message: string;
  timestamp_ms: number;
  file_url?: string;
  file_name?: string;
  file_type?: string;
}

export const getOfflineMessages = async (since?: number): Promise<Message[]> => {
  const token = localStorage.getItem('token');
  const params = new URLSearchParams();
  if (since) {
    params.append('since', since.toString());
  }

  const response = await fetch(`${API_BASE_URL}/api/messages?${params.toString()}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取离线消息失败' }));
    throw new Error(error.message || '获取离线消息失败');
  }

  const data = await response.json();
  return data.messages || [];
};

export const uploadFile = async (file: File): Promise<{ url: string; file_name: string; file_type: string }> => {
  const token = localStorage.getItem('token');
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch(`${API_BASE_URL}/api/upload`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
    body: formData,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '文件上传失败' }));
    throw new Error(error.message || '文件上传失败');
  }

  return response.json();
};

// 好友相关API
export const addFriend = async (friendIdOrUsername: string): Promise<void> => {
  const token = localStorage.getItem('token');
  const encodedId = encodeURIComponent(friendIdOrUsername);
  const response = await fetch(`${API_BASE_URL}/api/friends/${encodedId}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '添加好友失败' }));
    throw new Error(error.message || '添加好友失败');
  }
};

export const getFriends = async (): Promise<User[]> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${API_BASE_URL}/api/friends`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取好友列表失败' }));
    throw new Error(error.message || '获取好友列表失败');
  }

  const data = await response.json();
  const friends = data.friends || [];
  // 确保返回的用户ID是雪花ID（如果存在），否则使用数据库ID
  return friends.map((user: any) => ({
    id: user.snowflake_id?.toString() || user.id.toString(),
    name: user.name,
    email: user.email,
  }));
};

export const removeFriend = async (friendIdOrUsername: string): Promise<void> => {
  const token = localStorage.getItem('token');
  const encodedId = encodeURIComponent(friendIdOrUsername);
  const response = await fetch(`${API_BASE_URL}/api/friends/${encodedId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '删除好友失败' }));
    throw new Error(error.message || '删除好友失败');
  }
};

